package com.cx.mall.customer.handler;

import com.cx.mall.api.order.OrderInfoFeign;
import com.cx.mall.common.entity.order.entity.OrderInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Slf4j
@Configuration
public class CustomerHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderInfoFeign orderInfoFeign;

    @Bean
    public Consumer<Message<String>> updateOrderStatusInput() {
        return message -> {
            log.info("consumer更新订单状态消息开始", message);
            String payload = message.getPayload();
            Map<String, Object> headers = message.getHeaders();

            String key = "QUE_" + (String) headers.get("ROCKET_MQ_MESSAGE_ID");
            if(redisTemplate.opsForValue().setIfAbsent(key, "1", 60, TimeUnit.SECONDS)){
                // 初始化请求上下文, 因为feign调用需要请求头,获取请求头需要request对象
                RequestAttributes attributes = new ServletRequestAttributes(new MockHttpServletRequest());
                RequestContextHolder.setRequestAttributes(attributes);
                try {
                    log.info("开始调用更新订单状态服务,更新成功");
                    OrderInfo orderInfo = new OrderInfo();
                    orderInfo.setOrderId(payload);
                    orderInfo.setStatus(1);  // 已支付
                    orderInfo.setPayType(1); // 支付宝
                    orderInfoFeign.update(orderInfo);
                } catch (Exception e) {
                    log.error("更新订单状态失败", e);
                    throw new RuntimeException(e);
                } finally {
                    // 必须清理上下文
                    RequestContextHolder.resetRequestAttributes();
                }
            }
        };
    }
}